import {
  getPage,
  getImage
} from '../../utils/config';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
import {
  promisify,
  http,
  $toast,
  $query
} from '../../utils/utils';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    getPage: getPage,
    getImage: getImage,
    loading: 0,
    logged: 0,
    userId: '',
    loadmore: false,
    loaddone: false,
    abnor: false,
    imgheights: {},
    curBannerHeight: 0,
    showtips: 0,
    xqList:[],
    isBottom:false,
    anlipage:1,
    anlipages:0,
    anliList:[],
    imgheightsUser:{}
  },

  handleGetAnliList(cb, a = false){
    let { 
      anlipage,
      anlipages,
      loaddone,
      abnor,
     } = this.data;
    http.post(api.default, {
      data: {
        action: 'GetAnliList',
        shopid: 0,
        pageindex: anlipage
      }
    }, a).then(res=>{
      const {
        data
      } = res.data;
      console.log('data-------',data)

      //是否加载完毕

      if (data.pages == 0)
        abnor = true;
      else
        abnor = false;
      if (anlipage == data.pages && !abnor) loaddone = true;
      this.setData({
        anlipages: data.pages,
        loaddone,
        abnor
      });
      cb && cb(data);
    })
  },

  // 点击头像跳转店铺首页
  gocompanydetail() {
    const data = this.data.ShopInfo;
    if (data.ShopId) {
      wxApi.navigateTo('/pages/companydetail/index', {
        id: data.ShopId
      });
    }
  },

  imageLoad: function (e) { //获取图片真实宽度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  /**
   * 返回上一页
   */
  goBackTap() {
    //存在上一页,关闭当前返回一层,//没有上一页，跳回首页
    this.data.getPages > 1 ? wxApi.navigateBack(1) : wxApi.switchTab(getPage.home);
  },
  govr() {
    let {
      linkurl
    } = this.data.info;
    if (linkurl == "" || linkurl == null)
      $toast("该店铺还未开通此服务！")
    else
      wxApi.navigateTo("/pages/web/web?id=" + linkurl);
  },
  gohome() {
    wx.switchTab({
      url: getPage.home,
    })
  },
  updateDot(data){
    let dots = data.detail.dots;
    this.setData({ dots })
  },
  callphone() {
    let {
      logged,
      shopInfo,
      showtips,
      contacters
    } = this.data;
    let _this = this;
    var itemList = [];
    contacters.forEach(element => {
      itemList.push(element.contacter + " " + element.tel);
    });
    if (logged) {
      if (showtips == 0) {
        wx.showModal({
          title: '防骗提醒',
          content: '陌生电话要警惕，要求转账不要理',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              _this.setData({
                showtips: 1
              });
              wx.showActionSheet({
                itemList: itemList,
                success(res) {
                  console.log(res.tapIndex);
                  wx.makePhoneCall({
                    phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
                    success: function () {
                      console.log("拨打电话成功！")
                    },
                    fail: function () {
                      console.log("拨打电话失败！")
                    }
                  })
                },
                fail(res) {
                  console.log(res.errMsg)
                }
              })
            }
          }
        })
      } else {
        wx.showActionSheet({
          itemList: itemList,
          success(res) {
            console.log(res.tapIndex);
            wx.makePhoneCall({
              phoneNumber: contacters[res.tapIndex].tel, //此号码仅用于测试 。
              success: function () {
                console.log("拨打电话成功！")
              },
              fail: function () {
                console.log("拨打电话失败！")
              }
            })
          },
          fail(res) {
            console.log(res.errMsg)
          }
        })

        console.log(this.data.contacters)
      }
    } else {
      this.jumpLogin();
    }
  },

  showDetailImg(e) {
    console.log(e)
    let cur_url = e.currentTarget.dataset.cur+ '?x-oss-process=image/resize,w_1000/quality,q_100/watermark,image_c2h1aXlpbi5wbmc=';
    let urls = this.data.xqList.map(m => {
      return m + '?x-oss-process=image/resize,w_1000/quality,q_100/watermark,image_c2h1aXlpbi5wbmc='
    })
    wx.previewImage({
      urls: urls,
      current: cur_url,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },

  gotousu() {
    let {
      logged,
      ShopInfo,
      info
    } = this.data;
    if (logged) {
      wxApi.navigateTo(getPage.tousu + "?id=" + ShopInfo.ShopId + "&name=" + ShopInfo.ShopName + "&type=案例"+"&title="+info.title);
    } else {
      this.jumpLogin();
    }
  },

  /**
   * 跳转登录页
   */
  jumpLogin() {
    wxApi.setStartPage({
      id: this.data.shopid
    });
    wxApi.navigateTo(getPage.login);
  },


  /**
   * 监听页面--滚动
   */
  scrollChange(e) {

  },
  onPreviewImage(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    var showmenu = true;
    const {
      swiper
    } = this.data;
    console.log(data.id);
    const item = swiper[data.id];
    wx.previewImage({
      urls: swiper.map((item) => api.imageCdn + item.picurl),
      current: api.imageCdn + item.picurl,
      showmenu,
      fail() {
        wx.showToast({
          title: '预览图片失败',
          icon: 'none'
        });
      },
    });
  },
  gochat() {
    var {
      logged,
      ShopInfo
    } = this.data;
    console.log(logged);
    if (logged) {
      wxApi.navigateTo(getPage.chat, {
        id: ShopInfo.ShopId,
        user_name:ShopInfo.ShopName,
        img:ShopInfo.picurl,
        touserid:ShopInfo.UserId
      });

    } else {
      this.jumpLogin();
    }

  },
  mediaload(e) {
    console.log('mediaload---------', e)
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    //计算的高度值  
    var viewHeight = 750 / ratio;
    var imgheight = viewHeight;
    var imgheights = this.data.imgheights;
    //把每一张图片的对应的高度记录到数组里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },

  imageLoadUser: function (e) { //获取图片真实宽度 
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //宽高比  
      ratio = imgwidth / imgheight;
    let bol = ratio > 1 ? true : false
    var imgheightsUser = this.data.imgheightsUser;
    imgheightsUser[e.target.dataset.id] = bol;
    this.setData({
      imgheightsUser: imgheightsUser
    })
  },

  // 去案例详情
  goanlidetail(e) {
    const data = e.currentTarget.dataset || e.target.dataset;
    if (data.id) {
      wxApi.navigateTo(getPage.anlidetail, {
        id: data.id
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    /**
     * 店铺id
     */
    if (JSON.stringify(options) !== '{}') {
      this.setData({
        id: options.id
      });
    }
    //获取路由数量
    this.setData({
      getPages: getCurrentPages().length
    })
    /**
     * 获取system信息
     */
    promisify(wx.getSystemInfo)().then(res => {
      //获取右上角胶囊信息
      this.setData({
        navbar: wx.getMenuButtonBoundingClientRect(),
        window: res,
      })
      console.log(this.data.window);
    });

    /**
     * 获取用户信息 
     */
    let logged, userId = '';
    app.getLogin().then((res) => {
      logged = res.code;
      userId = res.data.user.user_id;
    }).catch((res) => {
      logged = res;
    }).finally(() => {
      this.setData({
        logged,
        userId
      });
      /**
       * 获取店铺信息
       */
      let {
        id,
        pageSize,
        loaddone,
        abnor
      } = this.data;

      //第一部分数据加载
      http.post(api.default, {
        data: {
          action: 'getcaseinfo',
          id: id,
          userid: userId
        }
      }, false).then((res) => {
        const {
          data
        } = res.data;
        console.log(data);
        let swiper = []
        data.videolist.forEach(item=>{
          item.type = 1;
          swiper.push(item)
        })
        data.filelist.forEach(item=>{
          item.type = 0;
          swiper.push(item)
        })
        let xqArr =data.xqlist&& data?.xqlist.map(m => m.url)

        this.setData({
          info: data.info,
          swiper: swiper,
          xqList: xqArr,
          ShopInfo: data.ShopInfo,
        });
      });

      //请求数据
      this.handleGetAnliList((res) => {
        this.setData({
          anliList: res.list
        });
      })

    });

    /**
     * scrollTop
     */
    this.scrollTop = 0;
    this.scrollHeight = 0;

    /**
     * 获取收缩对象高度
     */
    $query.select('#headInfo', (data) => {
      this.headInfo = data;
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 电赞案例
   */
  followAnliClick(event) {
    let {
      xqid
    } = event.currentTarget.dataset
    var {
      logged,
      userId,
    } = this.data;
    console.log('xqid==========',xqid)
    if (logged) {
      http.post(api.default, {
        data: {
          action: 'like_xuqiu',
          userid: userId,
          id: xqid,
        }
      }).then((res) => {
        let {errmsg,data} = res.data;
        $toast(errmsg, {
          icon: 'success'
        });
        // 前端显示跟新收藏状态
        let anliArr = this.data.anliList;
        anliArr.forEach(item => {
          if (item.id == xqid) {
            item.is_like = data,
            item.likes_num = data?item.likes_num+1:item.likes_num-1
          }
        })
        this.setData({
          anliList: anliArr
        })
      })
    } else {
      this.goLogin();
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    console.log('到底了')
    let {
      anlipage,
      anlipages,
      loadmore
    } = this.data;
    console.log('anlipages',anlipages,anlipage)

    if (anlipages >= anlipage && !loadmore) {
      anlipage++;
      loadmore = false;

      //显示加载效果
      this.setData({
        anlipage,
        loadmore
      });
      wx.showNavigationBarLoading();

      //请求数据
      this.handleGetAnliList((res) => {
        console.log('底部---------getProductsInfo')
        let {
          anliList
        } = this.data;
        loadmore = false;
        this.setData({
          loadmore,
          anliList: anliList.concat(res.list)
        });
        //隐藏加载效果
        wx.hideNavigationBarLoading();
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let {ShopName,ShopId,UserId} = this.data.ShopInfo;
    var pageshare = getPage.anlidetail + "?id=" + this.data.id + "?picurl="+ this.data.ShopInfo.picurl+"?ShopName=" + ShopName +"?ShopId=" + ShopId+ "?UserId=" + UserId;
    var picurl = "";
    if (this.data.swiper.length > 0)
      picurl = api.imageCdn + this.data.swiper[0].picurl;
    return {
      title: `【可居-案例详情】${this.data.info.title}`,
      imageUrl: picurl,
      path: pageshare,
      success: function (res) {
        console.log('分享')
        //$toast(pageshare);
        if (res.errMsg == 'shareAppMessage:ok') { //转发成功
          $toast(pageshare);
          console.log('分享成功')
          if (res.hasOwnProperty('shareTickets')) { //分享到群

          } else { // 分享到个人

          }

        } else { //转发失败
          console.log("分享失败");
        }
      }
    }
  }
})